// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var css_param = require("./updatePickup.css");
	var router = require("../hash/pageRouter");
	var tools = require("tools");
	var enterpriseId;
	var pickupMethod;
	var invoiceType;
	var financeNumber;
	var enterpriseName;
	var databind = require("databind");
	var constant = require("constant");
	var pickupId;
	var productTypes;
	var pageIndex = 1,
        pageSize = 10,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
    var html_bulkstockInfo = require("./html_bulkstockInfo_2.html");//查询货物弹出框内容
    var html_commonlyInfo = require("./html_commonlyInfo.html");
    var init = function(page) {
		pickupId = page.params.pickupId || base.getUrlParam("pickupId");
		initPickUpDetail(pickupId);
		initEvent();
	};
	var initEvent = function() {
		$("#updatePickup").on("change", "input[name=financePrices]", function(){
			var $this = $(this);
			if (!isNaN($this.parents("tr").find("input[name=financePrices]").val()) && !isNaN($this.parents("tr").find("input[name=pickupQuantitys]").val())) {
				$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=financePrices]").val()*$this.parents("tr").find("input[name=pickupQuantitys]").val());
				$this.parents("tr").find("input[name=pickupAmounts]").val($this.parents("tr").find("input[name=financePrices]").val()*$this.parents("tr").find("input[name=pickupQuantitys]").val());
			}
		});
		
		$("#updatePickup").on("change", "input[name=others]", function(){
			var $this = $(this);
			if (!isNaN($this.parents("tr").find("input[name=bulkstockAmounts]").val()) && !isNaN($this.parents("tr").find("input[name=interests]").html()) && !isNaN($this.parents("tr").find("input[name=others]").html())) {
				$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
				$this.parents("tr").find("input[name=pickupAmounts]").val($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
			}
		});
		
		$("#updatePickup").on("change", "input[name=interests]", function(){
			var $this = $(this);
			if (!isNaN($this.parents("tr").find("input[name=bulkstockAmounts]").val()) && !isNaN($this.parents("tr").find("input[name=interests]").html()) && !isNaN($this.parents("tr").find("input[name=others]").html())) {
				$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
				$this.parents("tr").find("input[name=pickupAmounts]").val($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
			}
		});
		
		$("#updatePickup").on("change", "input[name=bulkstockAmounts]", function(){
			var $this = $(this);
			if (!isNaN($this.parents("tr").find("input[name=bulkstockAmounts]").val()) && !isNaN($this.parents("tr").find("input[name=interests]").html()) && !isNaN($this.parents("tr").find("input[name=others]").html())) {
				$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
				$this.parents("tr").find("input[name=pickupAmounts]").val($this.parents("tr").find("input[name=interests]").val()*1 + $this.parents("tr").find("input[name=others]").val()*1 + $this.parents("tr").find("input[name=bulkstockAmounts]").val()*1);
			}
		});
		
		$("#updatePickup .commonlyInfo").unbind("click").click(function(){
			var ii = layer.open({
			  title: '常用信息',
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
			  area: ['1000px', '650px'], //宽高
			  content: html_commonlyInfo,
			  btn: ['确定', '取消'],
			  yes: function(){
				databind.fillForm($("#updatePickup .invoiceInfo"), ds[$(".html_commonlyInfo input[name=selected]:checked").parents("tr").attr("index")]);
				layer.close(ii);
			  }
			});
			
			var oData = {
				pageIndex: pageIndex,
				pageSize: pageSize,
				totalPageCount: 0
			};
			
			$(".html_commonlyInfo .search").unbind("click").click(function(){
				oData = {
					pageIndex: pageIndex,
					pageSize: pageSize,
					totalPageCount: 0,
					invoiceEnterpriseName: $(".html_commonlyInfo input[name]").val()
				};
				tools.loadList("inquireEnterpriseInvoiceInfoPageList.json", $(".html_commonlyInfo .dataBody"), $(".html_commonlyInfo .dataTpl"), oData, function(data){
					ds = data.datas;
				}, $(".html_commonlyInfo .pagerCon"));
			});
			
			tools.loadList("inquireEnterpriseInvoiceInfoPageList.json", $(".html_commonlyInfo .dataBody"), $(".html_commonlyInfo .dataTpl"), oData, function(data){
				ds = data.datas;
			}, $(".html_commonlyInfo .pagerCon"));
		});
		
		tools.loadSelectList($("#updatePickup select[name=enterpriseId]"), "inquireEnterpriseList.json", "id", "name", null);
		
		//选中委托方
		if(enterpriseId > 0) {
			$("#updatePickup select[name=enterpriseId]").find('option[value="' + enterpriseId + '"]').attr("selected",true);
		}
		
		//选中提货方式
		if(pickupMethod != undefined || pickupMethod != "") {
			$("#updatePickup select[name=pickupMethod]").find('option[value="' + pickupMethod + '"]').attr("selected",true);
		}
		
		//添加货物
		$("#updatePickup .addBulkstockInfo").unbind("click").click(function(){
			var ii = layer.open({
			  title: '添加货物信息',
			  type: 1,
			  skin: 'layui-layer-rim', //加上边框
			  area: ['1000px', '600px'], //宽高
			  content: html_bulkstockInfo,
			  btn: ['确定', '取消'],
			  yes: function(){
			  	if ($(".html_bulkstockInfo .check:checked").length > 0) {
				  	var i = 1;
				  	$.each($(".html_bulkstockInfo .check:checked"), function() {
				  		var $this = $(this);
				  		var tr = $(this).parents("tr").clone();
				  		tr.find(".check").parent().remove();
				  		tr.find(".index").html(i);
//				  		tr.append("<td><a href='javascript:void(0);' class='delete'>删除</a></td>");
				  		
				  		tr.find(".pickupAmount").parent().append("<input type='hidden' name='pickupAmounts'/>");
				  		
				  		tr.find("input[name=pickupQuantitys]").parent().append(tr.find("input[name=pickupQuantitys]").val());
				  		
//				  		tr.find("input[name=bulkstockAmounts]").parent().append(tr.find("input[name=bulkstockAmounts]").val());
				  		
//				  		tr.find("input[name=interests]").parent().append(tr.find("input[name=interests]").val());
					
				  		$("#updatePickup .table").append(tr);
				  		i++;
				  	});
				  	layer.close(ii);
			  	} else {
					base.alert(2, "请选择货物！");
				}
			  	
			  	tools.clearNoNumAll($("#updatePickup"));
			  	
			  	if ($("#updatePickup .table tr").length > 1) {
					$("#updatePickup select[name=enterpriseId]").attr("disabled", "disabled");
				} else {
					$("#updatePickup select[name=enterpriseId]").removeAttr("disabled");
				}
			  	totalInfo();
			  }
			});
			
			tools.loadSelectList($(".html_bulkstockInfo select[name=bulkstockInfoId]"), "inquireBulkstockPageList.json?pageSize=1000", "bulkstockInfoId", "bulkstockName", "specificationName");
			tools.loadSelectList($(".html_bulkstockInfo select[name=warehouseName]"), "inquireWarehouseList.json?enterpriseId=" + enterpriseId, "text", "text", null);
			$(".html_bulkstockInfo span[name=enterpriseName]").html(enterpriseName);
			$(".html_bulkstockInfo input[name=enterpriseId]").val(enterpriseId);
			$(".html_bulkstockInfo select[name=productType]").val(productTypes);
			$(".html_bulkstockInfo input[name=financeNumber]").val(financeNumber);
//			inquireBulkstockInventoryList
//			$(".createBailReturn input[name=financeId]").val(financeId);
//			tools.clearNoNumAll($(".createBailReturn"));

			$(".html_bulkstockInfo .search").unbind("click").click(function(){
				databind.submitDom($(".html_bulkstockInfo"), function(data){
					juicer.register("getValueByKey", constant.getValueByKey);
					var tpl = $(".html_bulkstockInfo .dataTpl").html();
					var html = juicer(tpl, data);
					$(".html_bulkstockInfo .dataBody").html(html);
					
					$.each($(".html_bulkstockInfo .check"), function() {
						var $this1 = $(this).parents("tr");
						$.each($("#updatePickup table tr"), function(){
							var $this2 = $(this);
							if (($this1.find("input[name=locationIds]").val() != null && $this2.find("input[name=locationIds]").val() != null) && $this1.find("input[name=locationIds]").val() == $this2.find("input[name=locationIds]").val()) {
								if (($this1.find("input[name=financeIds]").val() != null && $this2.find("input[name=financeIds]").val() != null) && $this1.find("input[name=financeIds]").val() == $this2.find("input[name=financeIds]").val()) {
									$this1.find("input").attr("disabled", "disabled");
								}
							}
						});
					});
				});
			});
			
			$(".html_bulkstockInfo").on("change", "input[name=financePrices]", function(){
				var $this = $(this);
				if (!isNaN($this.parents("tr").find("input[name=financePrices]").val()) && !isNaN($this.parents("tr").find("input[name=pickupQuantitys]").val())) {
					$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=financePrices]").val()*$this.parents("tr").find("input[name=pickupQuantitys]").val());
				}
			});
			
			$(".html_bulkstockInfo").on("change", "input[name=pickupQuantitys]", function(){
				var $this = $(this);
				if (!isNaN($this.parents("tr").find("input[name=financePrices]").val()) && !isNaN($this.parents("tr").find("input[name=pickupQuantitys]").val())) {
					$this.parents("tr").find(".pickupAmount").html($this.parents("tr").find("input[name=financePrices]").val()*$this.parents("tr").find("input[name=pickupQuantitys]").val());
				}
			});
		});
		
		//添加附件
			tools.fileupload($("#updatePickup #filesUuid"), null, function(data){
			var str = '<span class="showFiles"><a target="_blank" class="mas" fileUuid="' + data.result.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.result.data[0].fileUuid + '" class="showProductIntro">' + data.result.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="removeFile">x</a></span>';
			$("#updatePickup .addfile").before(str);
			var fs = [];
			$.each($('#updatePickup .mas'), function() {
				fs.push($(this).attr("fileUuid"));
			});
			$("#updatePickup input[name=filesUuid]").val(fs);
		});
		
		$("#updatePickup").on("click", ".removeFile", function(){
			$(this).parents(".showFiles").remove();
			var fs = [];
			$.each($('#updatePickup .mas'), function() {
				fs.push($(this).attr("fileUuid"));
			});
			$("#updatePickup input[name=filesUuid]").val(fs);
		});
		
		//删除货物
		$("#updatePickup").on("click", ".delete", function() {
			$(this).parents("tr").remove();
			
			if ($("#updatePickup .table tr").length > 1) {
				$("#updatePickup select[name=enterpriseId]").attr("disabled", "disabled");
			} else {
				$("#updatePickup select[name=enterpriseId]").removeAttr("disabled");
			}
			totalInfo();
		});
		
		//提交
		$("#updatePickup .sure").unbind("click").click(function(){
			$("#updatePickup input[name=enterpriseId]").val(enterpriseId);
			databind.submitDom($("#updatePickup"), function(){
				base.alert(1, "提交成功!");
				router.route("account/warehousePickupList.html?pickupState=0");
			});
		});
		
		//取消
//		$("#updatePickup .cancel").unbind("click").click(function(){
//			router.route("warehousePickup/wareHousePickupList.html");
//		});
		
	};
	
	
	//提货详情
	var initPickUpDetail = function(pickupId) {
		base.fnAjax({
			action: "inquireFinancePickupApplicationWarehouse.json",
			async: false,
			oData: {
				pickupId: pickupId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if(data.datas.length > 0) {
						juicer.register("getValueByKey", constant.getValueByKey);
						enterpriseId = data.datas[0].enterpriseId;
						pickupMethod = data.datas[0].pickupMethod;
						financeNumber =data.datas[0].bulkstockList[0].financeNumber;
						enterpriseName =data.datas[0].enterpriseName;
						invoiceType = data.datas[0].invoiceType;
						productTypes = data.datas[0].productType;
						var pickUpInfoTmpl = $("#updatePickup #pickUpInfoTmpls").html();
						var html = juicer(pickUpInfoTmpl, data);
						$("#updatePickup .content1").html(html);
						
						//发票信息
						if(invoiceType != undefined || invoiceType != "") {
							$("#updatePickup input[name=invoiceType]").removeAttr("checked");
							$("#updatePickup input[name=invoiceType][value="+ invoiceType +"]").prop("checked", "checked");
						}
						
						//发票类型点击事件
						$("#updatePickup input[name=invoiceType]").unbind("click").click(function(){
							if ($(this).val() == "0") {
								$("#updatePickup .invoiceInfo1").html("");
							} else if ($(this).val() == "1"){
								var str = '<div class="dataLine">				<div class="requireInput">					公司名称:<input type="text" isNull="1" codeName="公司名称" name="invoiceEnterpriseName" placeholder="请输入公司名称"/>				</div>				<div>				</div>			</div>			<div class="dataLine">				<div class="requireInput">					纳税识别号:<input type="text" isNull="1" codeName="纳税识别号" name="invoiceTaxpayerNumber" placeholder="请输入纳税识别号"/>				</div>				<div>				</div>			</div>			<div class="dataLine">				<div class="requireInput">					地址、电话:<input type="text" isNull="1" codeName="地址、电话" name="invoiceAddress" placeholder="请输入地址、电话"/>				</div>				<div>				</div>			</div>			<div class="dataLine">				<div class="requireInput">					开户行及账号:<input type="text" isNull="1" codeName="开户行及账号" name="invoiceAccount" placeholder="请输入开户行及账号"/>				</div>				<div>				</div>			</div>';
								$("#updatePickup .invoiceInfo1").html(str);
							} else if ($(this).val() == "2") {
								var str = '<div class="dataLine">				<div class="requireInput">					公司名称:<input type="text" isNull="1" codeName="公司名称" name="invoiceEnterpriseName" placeholder="请输入公司名称"/>				</div>				<div>				</div>			</div>			<div class="dataLine">				<div class="requireInput">					纳税识别号:<input type="text" isNull="1" codeName="纳税识别号" name="invoiceTaxpayerNumber" placeholder="请输入纳税识别号"/>				</div>				<div>				</div>			</div>';
								$("#updatePickup .invoiceInfo1").html(str);
							}
						});
						
						databind.fillForm($("#updatePickup .invoiceInfo"), data.datas[0]);
						
						if(data.datas[0].filesUuid != undefined) {
							var filesUuid = data.datas[0].filesUuid;
							$.each(filesUuid.split(","), function() {
								var _this = this;
								if($.trim(_this) != "") {
									var str = '<span class="showFiles"><a target="_blank" class="mas" fileUuid="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '" class="showProductIntro">' + tools.inquireFile(_this) + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="removeFile">x</a></span>';
									$("#updatePickup .addfile").before(str);
								}
							});
						}
					totalInfo();	
					}
				}else {
					base.alert(2, "获取信息失败");
					return;
				}
			}
		});
	};
	
	//提货货物合计信息
	var totalInfo = function() {
		var supervisionQuantitys = 0;
		$.each($("#updatePickup input[name='supervisionQuantitys']"), function() {
			supervisionQuantitys += parseFloat($(this).val());
		});
		$("#updatePickup #supervisionQuantitys").html(supervisionQuantitys);
		
		var pickupQuantitys = 0;
		$.each($("#updatePickup input[name='pickupQuantitys']"), function() {
			pickupQuantitys += parseFloat($(this).val());
		});
		$("#updatePickup #pickupQuantitys").html(pickupQuantitys);
		
		var pickupAmounts = 0;
		$.each($("#updatePickup input[name='pickupAmounts']"), function() {
			pickupAmounts += parseFloat($(this).val());
		});
		$("#updatePickup #pickupAmounts").html(pickupAmounts);
	};
	
	
	return {
		init: init
	};
});